package com.qpl.depression.cms.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qpl.depression.cms.common.ServerResponse;
import com.qpl.depression.cms.entity.Article;
import com.qpl.depression.cms.service.ArticleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 文章列表页面
     *
     * @return 列表页面
     */
    @GetMapping("article/list")
    public String addArticlePage() {
        return "articleList";
    }

    /**
     * 获取文章列表数据
     *
     * @param title 根据文章名模糊查询
     * @return 返回数据
     */
    @GetMapping("article/data")
    @ResponseBody
    public ServerResponse articleData(String title) {
        List<Article> list = articleService.list(Wrappers.<Article>lambdaQuery().like(StringUtils.isNoneBlank(title), Article::getArticleName, title));
        return ServerResponse.createBySuccess("success", list);
    }

    /**
     * 根据文章id编辑文章
     *
     * @param id    文章id
     * @param model 文章详情
     * @return 编辑页面
     */
    @GetMapping("/article/edit")
    public String blogEdit(@RequestParam("id") Integer id, Model model) {
        Article article = articleService.getById(id);
        model.addAttribute("blog", article);
        return "/articleEditPage";
    }

    /**
     * 添加文章页面
     *
     * @return 添加页面
     */
    @GetMapping("/article/add")
    public String blogAdd() {
        return "articleAddPage";
    }

    /**
     * 新增或者更新 文章
     *
     * @param article 文章内容
     * @return 操作结果
     */
    @PostMapping("article/save")
    @ResponseBody
    public ServerResponse articleSave(Article article) {
        return articleService.saveOrUpdate(article) ? ServerResponse.createBySuccessMessage("成功") : ServerResponse.createByErrorMessage("失败");
    }

    /**
     * 根据文章id删除文章
     *
     * @param id 文章id
     * @return 删除结果
     */
    @GetMapping("del")
    @ResponseBody
    public ServerResponse del(Long id) {
        return articleService.removeById(id) ? ServerResponse.createBySuccessMessage("成功") : ServerResponse.createByErrorMessage("失败");
    }

}
